<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="mobx-state-tree,">





  <link rel="alternate" href="/blog/atom.xml" title="编程那点事" type="application/atom+xml">






<meta name="description" content="定义Model时，需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍，方便同学们在定义props时挑选正确的类型。 前提定义props之前，有一个前提是，你已经明确地知道这个Model中状态的数据类型。 如果Model用于存放由后端API返回的数据，那么一定要和后端确认返回值在所有情况下的类型。比如，某个字段在没有值的时候你以为会给一个’’，而后端">
<meta name="keywords" content="mobx-state-tree">
<meta property="og:type" content="article">
<meta property="og:title" content="[MobX State Tree数据组件化开发][3]：选择正确的types.xxx">
<meta property="og:url" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-3-：选择正确的types-xxx/index.html">
<meta property="og:site_name" content="编程那点事">
<meta property="og:description" content="定义Model时，需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍，方便同学们在定义props时挑选正确的类型。 前提定义props之前，有一个前提是，你已经明确地知道这个Model中状态的数据类型。 如果Model用于存放由后端API返回的数据，那么一定要和后端确认返回值在所有情况下的类型。比如，某个字段在没有值的时候你以为会给一个’’，而后端">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-3-：选择正确的types-xxx/168a311b49e356b1.jpg">
<meta property="og:updated_time" content="2019-10-07T10:25:03.055Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[MobX State Tree数据组件化开发][3]：选择正确的types.xxx">
<meta name="twitter:description" content="定义Model时，需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍，方便同学们在定义props时挑选正确的类型。 前提定义props之前，有一个前提是，你已经明确地知道这个Model中状态的数据类型。 如果Model用于存放由后端API返回的数据，那么一定要和后端确认返回值在所有情况下的类型。比如，某个字段在没有值的时候你以为会给一个’’，而后端">
<meta name="twitter:image" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-3-：选择正确的types-xxx/168a311b49e356b1.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-3-：选择正确的types-xxx/">





  <title>[MobX State Tree数据组件化开发][3]：选择正确的types.xxx | 编程那点事</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">编程那点事</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://lhweb.gitee.io/blog/blog/2019/10/07/MobX-State-Tree数据组件化开发-3-：选择正确的types-xxx/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lhweb">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="编程那点事">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">[MobX State Tree数据组件化开发][3]：选择正确的types.xxx</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-10-07T17:53:53+08:00">
                2019-10-07
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>定义Model时，需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍，方便同学们在定义props时挑选正确的类型。</p>
<h2 id="前提"><a href="#前提" class="headerlink" title="前提"></a>前提</h2><p>定义props之前，有一个前提是，你已经明确地知道这个Model中状态的数据类型。</p>
<p>如果Model用于存放由后端API返回的数据，那么一定要和后端确认返回值在所有情况下的类型。比如，某个字段在没有值的时候你以为会给一个’’，而后端却给了个null；或者某个数组你以为会给你一个空数组[]，他又甩你一个null。如果你不打算自己编写一个标准化数据的方法，那一定要和数据的提供方确定这些细节。</p>
<h2 id="基础类型"><a href="#基础类型" class="headerlink" title="基础类型"></a>基础类型</h2><h3 id="types-string"><a href="#types-string" class="headerlink" title="types.string"></a>types.string</h3><p>定义一个字符串类型字段。</p>
<h3 id="types-number"><a href="#types-number" class="headerlink" title="types.number"></a>types.number</h3><p>定义一个数值类型字段。</p>
<h3 id="types-boolean"><a href="#types-boolean" class="headerlink" title="types.boolean"></a>types.boolean</h3><p>定义一个布尔类型字段。</p>
<h3 id="types-integer"><a href="#types-integer" class="headerlink" title="types.integer"></a>types.integer</h3><p>定义一个整数类型字段。</p>
<p>注意，即使是TypeScript中也没有“整数”这个类型，在编码时，传入一个带小数的值TypeScript也无法发现其中的类型错误。如无必要，请使用types.number。</p>
<h3 id="types-Date"><a href="#types-Date" class="headerlink" title="types.Date"></a>types.Date</h3><p>定义一个日期类型字段。</p>
<p>这个类型存储的值是标准的Date对象。在设置值时，可以选择传入数值类型的时间戳或者Date对象。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">export const Model = types</span><br><span class="line">    .model(&#123;</span><br><span class="line">        <span class="built_in">date</span>: types.<span class="built_in">Date</span> </span><br><span class="line">    &#125;)</span><br><span class="line">    .actions(<span class="built_in">self</span> =&gt; (&#123;</span><br><span class="line">        setDate (val: <span class="built_in">Date</span> | number) &#123;</span><br><span class="line">            <span class="built_in">self</span>.<span class="built_in">date</span> = <span class="built_in">date</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<h3 id="types-null"><a href="#types-null" class="headerlink" title="types.null"></a>types.null</h3><p>定义一个值为null的类型字段。</p>
<h3 id="types-undefined"><a href="#types-undefined" class="headerlink" title="types.undefined"></a>types.undefined</h3><p>定义一个值为undefined的类型字段。</p>
<h2 id="复合类型"><a href="#复合类型" class="headerlink" title="复合类型"></a>复合类型</h2><h3 id="types-model"><a href="#types-model" class="headerlink" title="types.model"></a>types.model</h3><p>定义一个对象类型的字段。</p>
<h3 id="types-array"><a href="#types-array" class="headerlink" title="types.array"></a>types.array</h3><p>定义一个数组类型的字段。<br><code>types.array(types.string);</code></p>
<p>上面的代码定义了一个字符串数组的类型。</p>
<h3 id="types-map"><a href="#types-map" class="headerlink" title="types.map"></a>types.map</h3><p>定义一个map类型的字段。该map的key都为字符串类型，map的值都为指定类型。</p>
<p><code>types.map(types.number);</code></p>
<h2 id="可选类型，types-optional"><a href="#可选类型，types-optional" class="headerlink" title="可选类型，types.optional"></a>可选类型，types.optional</h2><p>根据传入的参数，定义一个带有默认值的可选类型。</p>
<p>types.optional是一个方法，方法有两个参数，第一个参数是数据的真实类型，第二个参数是数据的默认值。</p>
<p><code>types.optional(types.number, 1);</code></p>
<p>上面的代码定义了一个默认值为1的数值类型。</p>
<p>注意，types.array或者types.map定义的类型自带默认值（array为[]，map为{}），也就是说，下面两种定义的结果是一样的：</p>
<figure class="highlight elm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">// 使用types.optional</span><br><span class="line">types.optional(types.array(types.number), []);</span><br><span class="line">types.optional(types.map(types.number), &#123;&#125;);</span><br><span class="line"></span><br><span class="line">// 不使用types.optional</span><br><span class="line">types.array(types.number);</span><br><span class="line">types.map(types.number);</span><br></pre></td></tr></table></figure>
<p>如果要设置的默认值与types.array或types.map自带的默认值相同，那么就不需要使用types.optional。</p>
<h2 id="自定义类型-types-custom"><a href="#自定义类型-types-custom" class="headerlink" title="自定义类型 types.custom"></a>自定义类型 types.custom</h2><p>如果想控制类型更底层的如序列化和反序列化、类型校验等细节，或者根据一个class或interface来定义类型，可以使用types.custom定义自定义类型。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">class <span class="built_in">Decimal</span> &#123;</span><br><span class="line">    <span class="params">...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const DecimalPrimitive = types.custom&lt;<span class="built_in">string</span>, <span class="built_in">Decimal</span>&gt;(&#123;</span><br><span class="line">    name: <span class="string">"Decimal"</span>,</span><br><span class="line">    fromSnapshot(value: <span class="built_in">string</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">new</span> <span class="built_in">Decimal</span>(value)</span><br><span class="line">    &#125;,</span><br><span class="line">    toSnapshot(value: <span class="built_in">Decimal</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> value.toString()</span><br><span class="line">    &#125;,</span><br><span class="line">    isTargetType(value: <span class="built_in">string</span> | <span class="built_in">Decimal</span>): <span class="built_in">boolean</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> value instanceof <span class="built_in">Decimal</span></span><br><span class="line">    &#125;,</span><br><span class="line">    getValidationMessage(value: <span class="built_in">string</span>): <span class="built_in">string</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (/^-?\d+\.\d+$/.test(value)) <span class="keyword">return</span> <span class="string">""</span> <span class="comment">// OK</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">`'$&#123;value&#125;' doesn't look like a valid decimal number`</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面的代码定义了一个Decimal类型。</p>
<h2 id="联合类型，types-union"><a href="#联合类型，types-union" class="headerlink" title="联合类型，types.union"></a>联合类型，types.union</h2><p>实际开发中也许会遇到这样的情况：一个值的类型可能是字符串，也可能是数值。那我们就可以使用types.union定义联合类型：</p>
<p><code>types.union(types.number, types.string);</code></p>
<p>联合类型可以有任意个联合的类型。</p>
<h2 id="字面值类型，types-literal"><a href="#字面值类型，types-literal" class="headerlink" title="字面值类型，types.literal"></a>字面值类型，types.literal</h2><p>字面值类型可以限制存储的内容与给定的值严格相等。</p>
<p>比如使用types.literal(‘male’)定义的状态值只能为’male’。</p>
<p>实际上，上面提到过的types.null以及types.undefined就是字面值类型：</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> NullType = types.literal(<span class="literal">null</span>);</span><br><span class="line"><span class="keyword">const</span> UndefinedType = types.literal(<span class="literal">undefined</span>);</span><br></pre></td></tr></table></figure>
<p>搭配联合类型，可以这样定义一个性别类型：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> GenderType = types.<span class="keyword">union</span>(types.literal(<span class="string">'male'</span>), types.literal(<span class="string">'female'</span>));</span><br></pre></td></tr></table></figure>
<h2 id="枚举类型，types-enumeration"><a href="#枚举类型，types-enumeration" class="headerlink" title="枚举类型，types.enumeration"></a>枚举类型，types.enumeration</h2><p>枚举类型可以看作是联合类型以及字面值类型的一层封装，比如上面的性别可以使用枚举类型来定义：</p>
<p><code>const GenderType = types.enumeration(&#39;Gender&#39;, [&#39;male&#39;, &#39;female&#39;]);</code></p>
<p>方法的第一个参数是可选的，表示枚举类型的名称。第二个参数传入的是字面值数组。</p>
<p>在TypeScript环境下，可以这样搭配TypeScript枚举使用：</p>
<figure class="highlight crystal"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">enum</span> <span class="title">Gender</span> &#123;</span></span><br><span class="line">    male,</span><br><span class="line">    female</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const GenderType = types.enumeration&lt;Gender&gt;(<span class="string">'Gender'</span>, Object.values(Gender));</span><br></pre></td></tr></table></figure>
<h2 id="可undefined类型，types-maybe"><a href="#可undefined类型，types-maybe" class="headerlink" title="可undefined类型，types.maybe"></a>可undefined类型，types.maybe</h2><p>定义一个可能为undefined的字段，并自带默认值undefined。</p>
<figure class="highlight fsharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">types.maybe(<span class="class"><span class="keyword">type</span>)</span></span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line">types.optional(types.union(<span class="class"><span class="keyword">type</span>, <span class="title">types</span>.<span class="title">literal</span></span>(undefined)), undefined)</span><br></pre></td></tr></table></figure>
<h2 id="可空类型，types-maybeNull"><a href="#可空类型，types-maybeNull" class="headerlink" title="可空类型，types.maybeNull"></a>可空类型，types.maybeNull</h2><p>与types.maybe类似，将undefined替换成了null。</p>
<figure class="highlight fsharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">types.maybeNull(<span class="class"><span class="keyword">type</span>)</span></span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line">types.optional(types.union(<span class="class"><span class="keyword">type</span>, <span class="title">types</span>.<span class="title">literal</span></span>(<span class="keyword">null</span>)), <span class="keyword">null</span>)</span><br></pre></td></tr></table></figure>
<h2 id="不可不类型，types-frozen"><a href="#不可不类型，types-frozen" class="headerlink" title="不可不类型，types.frozen"></a>不可不类型，types.frozen</h2><p>frozen意为“冻结的”，types.frozen方法用来定义一个immutable类型，并且存放的值必须是可序列化的。</p>
<p>当数据的类型不确定时，在TypeScript中通常将值的类型设置为any，而在MST中，就需要使用types.frozen定义。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">const Model = types</span><br><span class="line">    .model(<span class="string">'Model'</span>, &#123;</span><br><span class="line">        anyData: types.<span class="keyword">frozen</span>()</span><br><span class="line">    &#125;)</span><br><span class="line">    .actions(<span class="built_in">self</span> =&gt; (&#123;</span><br><span class="line">        setAnyData (<span class="built_in">data</span>: any) &#123;</span><br><span class="line">            <span class="built_in">self</span>.anyData = <span class="built_in">data</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<p>在MST看来，使用types.frozen定义类型的状态值是不可变的，所以会出现这样的情况：</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">model.anyData</span> = &#123;a: <span class="number">1</span>, b: <span class="number">2</span>&#125;<span class="comment">; // ok, reactive</span></span><br><span class="line"><span class="attr">model.anyData.b</span> = <span class="number">3</span><span class="comment">; // not reactive</span></span><br></pre></td></tr></table></figure>
<p>也就是只有设置一个新的值给这个字段，相关的observer才会响应状态的更新。而修改这个字段内部的某个值，是不会被捕捉到的。</p>
<h2 id="滞后类型，types-late"><a href="#滞后类型，types-late" class="headerlink" title="滞后类型，types.late"></a>滞后类型，types.late</h2><p>有时候会出现这样的需求，需要一个Model A，在A中，存在类型为A本身的字段。</p>
<p>如果这样写：</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> A = types</span><br><span class="line">    .model(<span class="string">'A'</span>, <span class="comment">&#123;</span></span><br><span class="line"><span class="comment">        a: types.maybe(A), // 使用mabe避免无限循环</span></span><br><span class="line"><span class="comment">    &#125;</span>);</span><br></pre></td></tr></table></figure>
<p>会提示Block-scoped variable ‘A’ used before its declaration，也就是在A定义完成之前就试图使用他，这样是不被允许的。</p>
<p><img src="/blog/2019/10/07/MobX-State-Tree数据组件化开发-3-：选择正确的types-xxx/168a311b49e356b1.jpg" alt></p>
<p>这个时候就需要使用types.late：</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">const A = types</span><br><span class="line">  .model(<span class="string">'A'</span>, &#123;</span><br><span class="line">    a: types.maybe(types.late(<span class="function"><span class="params">()</span> =&gt;</span> A))</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<p>types.late需要传入一个方法，在方法中返回A，这样就可以避开上面报错的问题。</p>
<h2 id="提纯类型，types-refinement"><a href="#提纯类型，types-refinement" class="headerlink" title="提纯类型，types.refinement"></a>提纯类型，types.refinement</h2><p>types.refinement可以在其他类型的基础上，添加额外的类型校验规则。</p>
<p>比如需要定义一个email字段，类型为字符串但必须满足email的标准格式，就可以这样做：</p>
<figure class="highlight mel"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">const EmailType = types.refinement(</span><br><span class="line">    <span class="string">'Email'</span>,</span><br><span class="line">    types.<span class="keyword">string</span>,</span><br><span class="line">    (<span class="keyword">snapshot</span>) =&gt; /^[a-zA-Z_1<span class="number">-9</span>]+@\.[a-z]+/.test(<span class="keyword">snapshot</span>), <span class="comment">// 校验是否符合email格式</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h2 id="引用与标识类型"><a href="#引用与标识类型" class="headerlink" title="引用与标识类型"></a>引用与标识类型</h2><p>拿上一篇文章中的TodoList作为例子，我们在对Todo列表中的某一个Todo进行编辑的时候，需要通过id跟踪这个Todo，在提交编辑结果时，通过这个id找到对应的Todo对象，然后进行更新。<br>这种需要跟踪、查找的需求很常见，写多了也觉得麻烦。<br>好在MST提供了一个优雅的解决方案：引用类型和标识类型。<br>这两者需要搭配使用才能发挥作用：</p>
<h3 id="定义标识，types-identifier"><a href="#定义标识，types-identifier" class="headerlink" title="定义标识，types.identifier"></a>定义标识，types.identifier</h3><p>标识就是数据对象的唯一标识字段，这个字段的值在库中保持唯一，也就是primary_key。</p>
<p>比如上一篇文章中的TodoItem，可以改造为：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> TodoItem = types</span><br><span class="line">  .model(<span class="string">'TodoItem'</span>, &#123;</span><br><span class="line">    id: types.identifier,</span><br><span class="line">    title: types.<span class="keyword">string</span>,</span><br><span class="line">    done: types.<span class="keyword">boolean</span>,</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<h3 id="使用引用类型进行跟踪，types-reference"><a href="#使用引用类型进行跟踪，types-reference" class="headerlink" title="使用引用类型进行跟踪，types.reference"></a>使用引用类型进行跟踪，types.reference</h3><p>改造TodoList：</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">export const TodoList = types</span><br><span class="line">  .model(<span class="string">'TodoList'</span>, &#123;</span><br><span class="line">    <span class="params">...</span></span><br><span class="line">    <span class="built_in">list</span>: types.<span class="built_in">array</span>(TodoItem),</span><br><span class="line">    editTarget: types.reference(TodoItem),</span><br><span class="line">    <span class="params">...</span></span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<p>然后在创建Model实例，或者applySnapshot的时候，可以将editTarget的值设定为正在编辑的TodoItem的id值，MST就会自动在list中查找id相同的TodoItem：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">const todoList = TodoList.create(&#123;</span><br><span class="line"><span class="symbol">   list:</span> [</span><br><span class="line">       &#123;<span class="string">id:</span> <span class="string">'1'</span>, <span class="string">title:</span> <span class="string">'Todo 1'</span>, <span class="string">done:</span> <span class="literal">true</span>&#125;,</span><br><span class="line">       &#123;<span class="string">id:</span> <span class="string">'2'</span>, <span class="string">title:</span> <span class="string">'Todo 2'</span>, <span class="string">done:</span> <span class="literal">true</span>&#125;,</span><br><span class="line">       ...</span><br><span class="line">   ],</span><br><span class="line"><span class="symbol">   editTarget:</span> <span class="string">'1'</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//此时的editTarget就是list中id为'1'的TodoItem对象</span></span><br><span class="line">console.log(todoList.list[<span class="number">0</span>] === todoList.editTarget); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line">todoList.editTarget = todoItem2; <span class="comment">// todoItem2为id为'2'的TodoItem对象</span></span><br><span class="line">console.log(getSnapshot(todoList).editTarget === <span class="string">'2'</span>); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line">todoList.editTarget = <span class="string">'2'</span> <span class="keyword">as</span> any;</span><br><span class="line">console.log(getSnapshot(todoList).editTarget === <span class="string">'2'</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>上面的代码说明，reference类型的字段本质上维护的是目标的标识字段值，并且，除了将目标对象赋值给reference字段外，将目标标识字段值赋值给reference字段的效果是一样的。</p>
<p>另外，reference不仅仅能搭配array使用，也能在map中查找：</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TodoList = types.model(<span class="string">'TodoList'</span>, &#123;</span><br><span class="line">    todoMap: types.<span class="built_in">map</span>(TodoItem),</span><br><span class="line">    editTarget: types.reference(TodoItem)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>甚至，MST也允许你自定义查找器（resolver），给types.reference指定第二个参数，比如官网的这个例子：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> User = types.model(&#123;</span><br><span class="line">    id: types.identifier,</span><br><span class="line">    name: types.<span class="keyword">string</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> UserByNameReference = types.maybeNull(</span><br><span class="line">    types.reference(User, &#123;</span><br><span class="line">        <span class="comment">// given an identifier, find the user</span></span><br><span class="line">        <span class="keyword">get</span>(identifier <span class="comment">/* string */</span>, parent: any <span class="comment">/*Store*/</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> parent.users.find(u =&gt; u.name === identifier) || <span class="literal">null</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// given a user, produce the identifier that should be stored</span></span><br><span class="line">        <span class="keyword">set</span>(<span class="keyword">value</span> <span class="comment">/* User */</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">value</span>.name</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Store = types.model(&#123;</span><br><span class="line">    users: types.array(User),</span><br><span class="line">    selection: UserByNameReference</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> s = Store.create(&#123;</span><br><span class="line">    users: [&#123; id: <span class="string">"1"</span>, name: <span class="string">"Michel"</span> &#125;, &#123; id: <span class="string">"2"</span>, name: <span class="string">"Mattia"</span> &#125;],</span><br><span class="line">    selection: <span class="string">"Mattia"</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="types-identifierNumber"><a href="#types-identifierNumber" class="headerlink" title="types.identifierNumber"></a>types.identifierNumber</h3><p>若对象的唯一标识字段的值为数值类型，那么可以使用types.identifierNumber代替types.identifier。</p>
<h3 id="types-safeReference"><a href="#types-safeReference" class="headerlink" title="types.safeReference"></a>types.safeReference</h3><p>这是一个“安全”的引用类型：</p>
<figure class="highlight elm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">const</span> <span class="type">Todo</span> = types.model(&#123; id: types.identifier &#125;)</span><br><span class="line"><span class="title">const</span> <span class="type">Store</span> = types.model(&#123;</span><br><span class="line">    todos: types.array(<span class="type">Todo</span>),</span><br><span class="line">    selectedTodo: types.safeReference(<span class="type">Todo</span>)</span><br><span class="line">&#125;)；</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/mobx-state-tree/" rel="tag"># mobx-state-tree</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/10/07/MobX-State-Tree数据组件化开发-2-：实例-TodoList/" rel="next" title="[MobX State Tree数据组件化开发][2]：实例-TodoList">
                <i class="fa fa-chevron-left"></i> [MobX State Tree数据组件化开发][2]：实例-TodoList
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/10/09/decorator修饰器语法/" rel="prev" title="decorator修饰器语法">
                decorator修饰器语法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">lhweb</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前提"><span class="nav-number">1.</span> <span class="nav-text">前提</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基础类型"><span class="nav-number">2.</span> <span class="nav-text">基础类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#types-string"><span class="nav-number">2.1.</span> <span class="nav-text">types.string</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-number"><span class="nav-number">2.2.</span> <span class="nav-text">types.number</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-boolean"><span class="nav-number">2.3.</span> <span class="nav-text">types.boolean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-integer"><span class="nav-number">2.4.</span> <span class="nav-text">types.integer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-Date"><span class="nav-number">2.5.</span> <span class="nav-text">types.Date</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-null"><span class="nav-number">2.6.</span> <span class="nav-text">types.null</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-undefined"><span class="nav-number">2.7.</span> <span class="nav-text">types.undefined</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#复合类型"><span class="nav-number">3.</span> <span class="nav-text">复合类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#types-model"><span class="nav-number">3.1.</span> <span class="nav-text">types.model</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-array"><span class="nav-number">3.2.</span> <span class="nav-text">types.array</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-map"><span class="nav-number">3.3.</span> <span class="nav-text">types.map</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#可选类型，types-optional"><span class="nav-number">4.</span> <span class="nav-text">可选类型，types.optional</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自定义类型-types-custom"><span class="nav-number">5.</span> <span class="nav-text">自定义类型 types.custom</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#联合类型，types-union"><span class="nav-number">6.</span> <span class="nav-text">联合类型，types.union</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字面值类型，types-literal"><span class="nav-number">7.</span> <span class="nav-text">字面值类型，types.literal</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#枚举类型，types-enumeration"><span class="nav-number">8.</span> <span class="nav-text">枚举类型，types.enumeration</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#可undefined类型，types-maybe"><span class="nav-number">9.</span> <span class="nav-text">可undefined类型，types.maybe</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#可空类型，types-maybeNull"><span class="nav-number">10.</span> <span class="nav-text">可空类型，types.maybeNull</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#不可不类型，types-frozen"><span class="nav-number">11.</span> <span class="nav-text">不可不类型，types.frozen</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#滞后类型，types-late"><span class="nav-number">12.</span> <span class="nav-text">滞后类型，types.late</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#提纯类型，types-refinement"><span class="nav-number">13.</span> <span class="nav-text">提纯类型，types.refinement</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#引用与标识类型"><span class="nav-number">14.</span> <span class="nav-text">引用与标识类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义标识，types-identifier"><span class="nav-number">14.1.</span> <span class="nav-text">定义标识，types.identifier</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用引用类型进行跟踪，types-reference"><span class="nav-number">14.2.</span> <span class="nav-text">使用引用类型进行跟踪，types.reference</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-identifierNumber"><span class="nav-number">14.3.</span> <span class="nav-text">types.identifierNumber</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#types-safeReference"><span class="nav-number">14.4.</span> <span class="nav-text">types.safeReference</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lhweb</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
